<template>
  <div class="container">
    <el-form class="form_box">
      <el-form-item label="角色名称">
        <el-input v-model="roleName" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item class="btn_box">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
        <el-button type="primary" @click="addRole">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" align="center">
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="roleName" label="用户名" show-overflow-tooltip></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="updateStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="changeRole(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="powerEdit(scope.row)">编辑权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 20, 30, 40]" :page-size="size"
        layout="prev, pager, next, jumper, sizes, total" :total="total">
      </el-pagination>
    </div>
    <el-dialog :visible.sync="editVisible" width="30%" :before-close="editClose" class="elDialog editBox">
      <p slot="title" class="elDialog-header">
        <span>添加/编辑</span>
      </p>
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop='remark'>
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editClose">取 消</el-button>
        <el-button type="primary" @click="role">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="powerVisible" width="50%" class="elDialog roleMenu">
      <p slot="title" class="elDialog-header">
        <span>权限编辑</span>
      </p>
      <el-row>
        <el-col :span="8">
          <h2>菜单权限</h2>
          <el-tree :props="defaultProps" :data='data' show-checkbox @check-change="handleCheckChange" node-key='id'
            @node-click='selectMenu' ref="tree">
          </el-tree>
        </el-col>
        <el-col :span="16">
          <h2>功能权限</h2>
          <div class="grid-content bg-purple">
            <el-checkbox-group v-model="perIds">
              <el-checkbox v-for="item in permissions" :label="item.id" :key="item.id">
                {{item.permissionName}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="powerVisible = false">取 消</el-button>
        <el-button type="primary" @click="setPower">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { roleList, delRole, roleListPage, addRole, changeRole, roleStatus, roleEditInfo, roleMenu, savePower } from '../../../api/account';
import { getMenu } from '../../../api/index'
export default {
  name: 'role',
  data () {
    return {
      powerVisible: false,
      editVisible: false,
      roleName: '',
      id: '',
      page: 1,
      size: 10,
      total: 0,
      defaultProps: {
        children: 'childs',
        label: 'menuName'
      },
      form: {
        roleName: '',
        remark: ''
      },
      tableData: [],
      data: [],
      checked: [],
      perIds: [],
      permissions: [],
      params: [],
      rules: {
        roleName: [{ required: true, message: '请选择角色', trigger: 'change' }],
        // remark: [{ required: true, message: '请选择地区', trigger: 'change' }]
      }
    };
  },
  created () {
    this.getList()
  },
  methods: {
    editClose () {
      this.$refs.form.resetFields();
      this.editVisible = false
    },
    powerClose () {
      this.powerVisible = false;
    },
    // 选中菜单
    handleCheckChange (data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    // 编辑权限
    powerEdit (row) {
      this.id = row.id
      this.permissions = [];
      this.checked = []
      this.powerVisible = true;
      roleMenu(row.id).then(res => {
        if (res.success) {
          this.data = res.data;
          this.data.forEach(item => {
            if (item.id === '1' && item.canView) {
              this.checked.push(item.id)
            }
            if (item.childs && item.childs.length) {
              item.childs.forEach(i => {
                if (i.canView) {
                  this.checked.push(i.id)
                }
                if (i.permissions && i.permissions.length) {
                  i.permissions.forEach(a => {
                    if (a.hasPer) {
                      this.perIds.push(a.id)
                    }
                  })
                }
              })
            }
          });
          console.log(this.checked, this.perIds);
          this.$refs.tree.setCheckedKeys(this.checked)
          console.log(res.data);
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 点击菜单
    selectMenu (menu) {
      if (!menu.permissions) {
        this.permissions = [];
      }
      if (menu.level === 2) {
        this.permissions = menu.permissions;
        this.$refs.tree.setChecked(menu.id, true)
      }
      console.log(menu);

    },
    // 保存权限
    setPower () {
      let checked = this.$refs.tree.getCheckedKeys();
      let halfChecked = this.$refs.tree.getHalfCheckedKeys();
      let menuIds = checked.concat(halfChecked);
      let perIds = this.perIds
      savePower(this.id, { menuIds, perIds }).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          this.powerVisible = false;
          this.perIds = []
        } else {
          this.$message.error(`${res.msg}`)
        }
      })




    },
    // 获取列表
    getList () {
      let query = {}
      if (this.roleName) {
        query = {
          roleName: this.roleName
        }
      }
      roleListPage(this.page, this.size, query).then(res => {
        if (res.success) {
          this.tableData = res.data.records || []
          this.total = res.data.total
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 修改,添加提交
    role () {
      this.$refs.form.validate(valid => {
        if (valid) {
          (this.id ? changeRole(this.id, this.form) : addRole(this.form)).then(res => {
            if (res.success) {
              this.$message.success(this.id ? '修改成功' : "添加成功")
            } else {
              this.$message.error(`${res.msg}`)
            }
            this.editClose();
            this.getList()
          })
        }
      })
    },
    reset () {
      this.roleName = '';
      this.page = 1;
      this.size = 10;
      this.getList()
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getList();
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getList()
    },
    // 更改角色
    changeRole (row) {
      this.id = row.id;
      roleEditInfo(row.id).then(res => {
        if (res.success) {
          console.log(res.data);
          this.form = res.data;
          this.editVisible = true;
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    addRole () {
      // this.form = {
      //   roleName: '',
      //   remark: ''
      // };
      this.editVisible = true;
      this.id = ''
    },
    // delAccount () {
    //   this.$confirm('您要删除账号，删除后不可恢复，是否确定操作？', '信息提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //     callback: action => {
    //       if (action === 'confirm') {
    //         delAllfiles({ ads: this.selection.map(item => item.id).join(',') }).then(data => {
    //           console.log(data);
    //           if (data.success) {
    //             this.$message.success('删除成功');
    //           } else {
    //             this.$message.error(`${data.msg}`);
    //           }
    //         });
    //       }
    //     }
    //   });
    // },
    updateStatus (row) {
      roleStatus(row.id, row.status).then(data => {
        console.log(data);
      });
    }
  }
};
</script>

<style scoped>
.form_box .el-form-item {
    display: inline-block;
    margin-left: 20px;
}
.form_box .el-input {
    width: 200px;
}
.form_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.form_box .el-form-item {
    display: flex;
    align-items: center;
    flex-direction: row;
}
/* .el-form .btn_box {
    width: 100%;
    text-align: right;
    margin: 0px auto 20px;
} */
.el-form .btn_box .el-button {
    width: 105px;
    margin-left: 20px;
}
.el-table {
    height: 82%;
}
.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}

.page {
    width: 100%;
    height: 40px;
    background: #ffffff;
    text-align: center;
    padding-top: 20px;
}
.editBox .el-dialog .el-form-item /deep/ .el-input__inner {
    width: 100%;
}
.editBox .el-dialog .el-form-item /deep/ .el-input {
    width: 100%;
}
.editBox .el-dialog .el-form {
    padding-right: 30px;
}
.editBox .el-dialog .el-form-item /deep/ .el-select {
    width: 100%;
}
.editBox .el-dialog .dialog-footer .el-button {
    width: 100px;
    margin-right: 20px;
}
.roleMenu /deep/ .el-dialog__body {
    padding: 0 !important;
    margin: 0 !important;
}
.roleMenu .el-row {
    /* padding: 20px 30px; */
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
}
.roleMenu .el-col {
    padding: 0 30px 20px;
    border-right: 1px solid #eee;
}
.roleMenu h2 {
    margin-top: 10px;
    margin-bottom: 10px;
    font-size: 14px;
}
.roleMenu .el-checkbox {
    width: 100px;
}
.roleMenu .el-button {
    width: 100px;
}
</style>